﻿using System;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using WIA;

namespace PhotoIDScanner
{
    public partial class MainForm : Form
    {
        ImageFile image;
        public int scannedIDs=0;
        public int savedIDs=0;


        public MainForm()
        {
            InitializeComponent();
        }

        private void btnScan_Click(object sender, EventArgs e)
        {
            try
            {
                CommonDialogClass commonDialogClass = new CommonDialogClass();
                Device scannerDevice = commonDialogClass.ShowSelectDevice(WiaDeviceType.ScannerDeviceType, true, false);

                if (scannerDevice != null)
                {
                    Item scannerItem = scannerDevice.Items[1];

                    //set scanner settings
                    //AdjustScannerSettings(scannerItem, 300, 0, 0, 1060, 660, 0, 0, 1, 1);
                    AdjustScannerSettings(scannerItem, 300, 50, 25, 1007, 625, 0, 0, 1, 1);
                    //object scanResult = commonDialogClass.ShowTransfer(scannerItem, WIA.FormatID.wiaFormatPNG, false);
                    //MessageBox.Show("Please insert Photo ID into Scanner with strip facing up.", "Insert ID", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    frmInsertIDPrompt frmInsertIDPrompt = new frmInsertIDPrompt();
                    frmInsertIDPrompt.Location = new Point(this.Left + (this.Width / 2 - frmInsertIDPrompt.Width / 2), this.Top + (this.Height / 2 - frmInsertIDPrompt.Height / 2));
                    frmInsertIDPrompt.ShowDialog();

                    object scanResult = commonDialogClass.ShowTransfer(scannerItem, WIA.FormatID.wiaFormatJPEG, false);
                    //object scanResult = commonDialogClass.ShowAcquisitionWizard(scannerDevice);

                    if (scanResult != null)
                    {
                        image = (ImageFile)scanResult;
                        var imageBytes = (byte[])image.FileData.get_BinaryData();
                        var ms = new MemoryStream(imageBytes);
                        var img = Image.FromStream(ms);
                        pictureBoxScannedImage.Image = img;
                        btnSave.Enabled = true;

                        scannedIDs = scannedIDs + 1;
                    }
                }
            }
            catch (Exception ex)
            {
                /*if (ex.Message.Contains("0x80210015"))
                    MessageBox.Show("Hey!  Check your scanner connection and driver.\n\nPlease contact IT Support","Scanner Not Found", MessageBoxButtons.OK,MessageBoxIcon.Error);
                else if (ex.Message.Contains("0x80040154"))
                    MessageBox.Show("Microsoft WIA 2.0 dll not found.\n\nPlease contact IT Support", "Missing DLL", MessageBoxButtons.OK, MessageBoxIcon.Error);
                else if (ex.Message.Contains("0x80131418"))
                    MessageBox.Show("Microsoft WIA 2.0 dll not found.  Please contact IT Support");
                else if (ex.Message.Contains("0x80210015"))
                    MessageBox.Show("Scan process was canceled.  Please try again.","Scan Canceled", MessageBoxButtons.OK,MessageBoxIcon.Error);
                else*/
                    MessageBox.Show("Please contact IT Support.\nError Code: " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            frmSave saveAsDialog = new frmSave(this);
            saveAsDialog.Location = new Point(this.Left + (this.Width / 2 - saveAsDialog.Width / 2), this.Top + (this.Height / 2 - saveAsDialog.Height / 2));
            saveAsDialog.ShowDialog (this);
            scannedIDs = 0;
            savedIDs = 0;
        }

        //Set scanner settings
        private static void AdjustScannerSettings(IItem scannnerItem, int
            scanResolutionDPI, int scanStartLeftPixel, int scanStartTopPixel,
            int scanWidthPixels, int scanHeightPixels, int brightnessPercents, int contrastPercents, int imageIntent, int scannerType)
        {
            const string WIA_HORIZONTAL_SCAN_RESOLUTION_DPI = "6147";  //DPI
            const string WIA_VERTICAL_SCAN_RESOLUTION_DPI = "6148";  //DPI
            const string WIA_HORIZONTAL_SCAN_START_PIXEL = "6149";  //Starting position
            const string WIA_VERTICAL_SCAN_START_PIXEL = "6150";  //Staring position
            const string WIA_HORIZONTAL_SCAN_SIZE_PIXELS = "6151";  //Total pixals to scan
            const string WIA_VERTICAL_SCAN_SIZE_PIXELS = "6152";  //Total pixals to scan
            const string WIA_SCAN_BRIGHTNESS_PERCENTS = "6154";  //set from 0-100
            const string WIA_SCAN_CONTRAST_PERCENTS = "6155";  //set from 0-100
            const string WIA_IMAGE_INTENT = "6146";  //set to color=1,gray=2,bw=2, unspecified=0
            const string WIA_SCANNER_TYPE = "3088";  //set to ADF=1, Flatbed=2

            //SetWIAProperty(scannnerItem.Properties, WIA_SCANNER_TYPE, scannerType);
            SetWIAProperty(scannnerItem.Properties, WIA_IMAGE_INTENT, imageIntent);
            SetWIAProperty(scannnerItem.Properties, WIA_HORIZONTAL_SCAN_RESOLUTION_DPI, scanResolutionDPI);
            SetWIAProperty(scannnerItem.Properties, WIA_VERTICAL_SCAN_RESOLUTION_DPI, scanResolutionDPI);
            SetWIAProperty(scannnerItem.Properties, WIA_HORIZONTAL_SCAN_START_PIXEL, scanStartLeftPixel);
            SetWIAProperty(scannnerItem.Properties, WIA_VERTICAL_SCAN_START_PIXEL, scanStartTopPixel);
            SetWIAProperty(scannnerItem.Properties, WIA_HORIZONTAL_SCAN_SIZE_PIXELS, scanWidthPixels);
            SetWIAProperty(scannnerItem.Properties, WIA_VERTICAL_SCAN_SIZE_PIXELS, scanHeightPixels);
            SetWIAProperty(scannnerItem.Properties, WIA_SCAN_BRIGHTNESS_PERCENTS, brightnessPercents);
            SetWIAProperty(scannnerItem.Properties, WIA_SCAN_CONTRAST_PERCENTS, contrastPercents);
        }

        private static void SetWIAProperty(IProperties properties, object propName, object propValue)
        {
            Property prop = properties.get_Item(ref propName);
            prop.set_Value(ref propValue);
        }

        private static void SaveImageToJPEGFile(ImageFile image, string fileName)
        {
            ImageProcess imgProcess = new ImageProcess();
            object convertFilter = "Convert";
            string convertFilterID = imgProcess.FilterInfos.get_Item(ref convertFilter).FilterID;
            imgProcess.Filters.Add(convertFilterID, 0);
            SetWIAProperty(imgProcess.Filters[imgProcess.Filters.Count].Properties, "FormatID", WIA.FormatID.wiaFormatJPEG);
            image = imgProcess.Apply(image);
            image.SaveFile(fileName);
        }

        private void MainForm_KeyDown(object sender, KeyEventArgs e)
        {
            /*byte[] keys = new byte[255];

            GetKeyboardState(keys);

            if (keys[(int)Keys.Up] == 129 && keys[(int)Keys.Right] == 129)
            {
                Console.WriteLine("Up Arrow key and Right Arrow key down.");
            }*/
        }

        private void button1_Click(object sender, EventArgs e)
        {


        }

        private void settingsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frmSettings frmSettings = new frmSettings();
            frmSettings.Location = new Point(this.Left + (this.Width / 2 - frmSettings.Width / 2), this.Top + (this.Height / 2 - frmSettings.Height / 2));
            frmSettings.ShowDialog();
        }

        private void MainForm_Load(object sender, EventArgs e)
        {

        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            DialogResult reply;
            if (scannedIDs > savedIDs)
            {
                reply = MessageBox.Show("Photo ID has not been saved.  Would you like to save this Photo ID?", "Save Photo ID?", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

                if (reply == DialogResult.Yes)
                {
                    frmSave saveAsDialog = new frmSave(this);
                    saveAsDialog.Location = new Point(this.Left + (this.Width / 2 - saveAsDialog.Width / 2), this.Top + (this.Height / 2 - saveAsDialog.Height / 2));
                    saveAsDialog.ShowDialog(this);
                    scannedIDs = 0;
                    savedIDs = 0;
                }
                else
                {
                    this.Close();
                }

            }
            else { this.Close(); }

            
        }

        private void button1_Click_1(object sender, EventArgs e)
        {

        }

        private void menuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {

        }

    }
}
